<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>场景联动</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="mg-top-20">
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="scenes" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
      style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="name" label="场景名称" width="200">
      </el-table-column>
      <el-table-column sortable prop="createAt" label="创建时间" width="150">
        <template slot-scope="scope">
          <div>{{scope.row.createAt|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="state" :formatter="stateFormat" label="状态" width="80">
      </el-table-column>
      <el-table-column :formatter="stateFormat" label="执行日志" width="100">
         <template slot-scope="scope">
          <el-button plain @click="handleShowLog(scope.row)" size="mini">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button v-if="scope.row.state=='running'" size="mini" type="danger" @click="handlePause(scope.$index, scope.row)">停止</el-button>
          <el-button v-if="scope.row.state=='stopped'" size="mini" type="success" @click="handleResume(scope.$index, scope.row)">启动</el-button>
          <el-popconfirm v-if="scope.row.state=='stopped'" title="确认要删除？" @confirm="handleDelete(scope.$index, scope.row)" class="mg-left-10">
              <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="80%" @click="closeDialog">
      <el-form label-width="120px" :rules="rules" :model="editForm" ref="editForm">
        <el-form-item label="场景名称" prop="name">
          <el-input size="small" v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="监听器" prop="listeners">
          <el-card class="box-card" v-for="listener in editForm.listeners" :key="listener.id" :body-style="{padding:'10px'}">
            <el-row>
              <el-col :span="22"><Listener :data="listener"></Listener></el-col>
              <el-col :span="2"><el-button size="small" type="error" @click="delListener(listener)">删除</el-button></el-col>
            </el-row>
          </el-card>
          <el-button size="small" @click="addListener()">新增</el-button>
        </el-form-item>
        <el-form-item label="过滤器" prop="filters">
          <el-card class="box-card" v-for="filter in editForm.filters" :key="filter.id" :body-style="{padding:'10px'}">
            <el-row>
              <el-col :span="22"><Filtera :data="filter"></Filtera></el-col>
              <el-col :span="2"><el-button size="small" type="error" @click="delAction(action)">删除</el-button></el-col>
            </el-row>
          </el-card>
          <el-button size="small" @click="addFilter()">新增</el-button>
        </el-form-item>
        <el-form-item label="输出" prop="actions">
          <el-card class="box-card" v-for="action in editForm.actions" :key="action.id" :body-style="{padding:'10px'}">
            <el-row>
              <el-col :span="22"><Action :data="action" :showAlarm="false" :showScene="false"></Action></el-col>
              <el-col :span="2"><el-button size="small" type="error" @click="delAction(action)">删除</el-button></el-col>
            </el-row>
          </el-card>
          <el-button size="small" @click="addAction()">新增</el-button>
        </el-form-item>
        <el-form-item label="场景描述" prop="desc">
          <el-input size="small" v-model="editForm.desc" auto-complete="off" type="textarea" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button :disabled="editForm.state=='running'" size="small" type="primary" :loading="loading" class="title" @click="submitEditForm('editForm')">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="场景执行日志" :visible.sync="showLogVisible" width="60%">
      <SceneLogs :sceneId="sceneId"></SceneLogs>
    </el-dialog>

  </div>
</template>

<script>
  import {uuid} from '../../utils/util.js'
  import Pagination from '../../components/Pagination'
  import Listener from './Listener.vue'
  import Filtera from './Filter.vue'
  import Action from './Action.vue'
  import SceneLogs from './SceneLogs.vue'
  import {SceneList,SceneSave,SceneDelete,ScenePause,SceneResume} from '@/api/ruleApi.js'
  export default {
    data() {
      var validateAction = (rule, value, callback) => {
        if (this.editForm.actions.length==0) {
          callback(new Error('请设置输出'));
        } else {
          callback();
        }
      };
      return {
        loading: false, //是显示加载
        title: '',
        scenes: [],
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
        editForm:{
          name: '',
          state: '',
          listeners: [],
          filters: [],
          actions:[],
          desc: ''
        },
        rules: {
          name: [
            { required: true, message: '请输入场景名称', trigger: 'blur' }
          ],
          actions: [
            { validator: validateAction, trigger: 'blur' }
          ]
        },
        editFormVisible: false,
        showLogVisible: false,
        sceneId: '',
      }
    },
    // 注册组件
    components: {
      Pagination,
      Listener,
      Filtera,
      Action,
      SceneLogs
    },
    /**
     * 数据发生改变
     */

    /**
     * 创建完毕
     */
    created() {
      this.getdata()
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      getdata(params) {
        SceneList(params).then(rst=>{
          this.scenes=rst;
        });
      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.limit = parm.pageSize
        this.getdata()
      },
      stateFormat(row, column, value){
        switch(value){
          case 'stopped':
            return '已停止';

          case 'running':
            return '运行中';
          
        }
      },
      handleShowResult(result){
        this.$alert(result, '执行结果', {
          confirmButtonText: '确定'
        });
      },
      handleAdd(){
        this.editFormVisible = true;
        this.title = '添加场景'
        this.editForm.id='';
        this.editForm.state='';
        this.editForm.name= '';
        this.editForm.listeners=[];
        this.editForm.filters=[];
        this.editForm.actions=[];
        this.editForm.desc='';
      },
      handleEdit(index, row) {
        this.editFormVisible = true;
        this.title = '编辑场景';
        this.editForm.id = row.id;
        this.editForm.state=row.state;
        this.editForm.name = row.name;
        this.editForm.desc = row.desc;

        let listeners=[];
        row.listeners.forEach(a=>{
          listeners.push(JSON.parse(a.config));
        })
        this.editForm.listeners = listeners;

        let filters=[];
        row.filters.forEach(a=>{
          filters.push(JSON.parse(a.config));
        })
        this.editForm.filters = filters;

        let actions=[];
        row.actions.forEach(a=>{
          actions.push(JSON.parse(a.config));
        })
        this.editForm.actions = actions;
      },
      handlePause(index,row){
        ScenePause(row.id).then(()=>{
          this.getdata();
        })
      },
      handleResume(index,row){
        SceneResume(row.id).then(()=>{
          this.getdata();
        })
      },
      handleDelete(index,row){
        SceneDelete(row.id).then(()=>{
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success'
          });
          this.getdata();
        })
      },
      addListener(){
        this.editForm.listeners.push({
          id: uuid(),
          type: 'device',
          topic: '',
          conditions: []
        });
      },
      delListener(listener){
        let idx=this.editForm.listeners.findIndex(l=>l.id==listener.id);
        this.editForm.listeners.splice(idx,1);
      },
      addFilter(){
        this.editForm.filters.push({
          id: uuid(),
          type: 'device',
          conditions: []
        });
      },
      addAction(){
        this.editForm.actions.push({
          id: uuid(),
          type: '',
          services: []
        });
      },
      delAction(action){
        let idx= this.editForm.actions.findIndex(o=>o.id==action.id);
        this.editForm.actions.splice(idx,1);
      },
      submitEditForm(from) {
        console.log(this.editForm);
        this.$refs[from].validate(valid => {
          if (valid) {
            this.editForm.listeners.forEach(l=>{
              l.config=JSON.stringify(l);
            });
            this.editForm.filters.forEach(f=>{
              f.config=JSON.stringify(f);
            });
            this.editForm.actions.forEach(a=>{
              a.config=JSON.stringify(a);
            });

            SceneSave(this.editForm).then(()=>{
              this.editFormVisible = false;
              this.loading = false;
              this.$message({
                type: 'success',
                message: '保存成功！'
              })
              this.getdata();
              this.editFormVisible=false;
            })
          }
        })
      },
      closeDialog() {
        this.editFormVisible = false
      },
      handleShowLog(row){
        this.sceneId=row.id;
        this.showLogVisible=true;
      },
    }
}
</script>